import { login, sysProfile, sysUser } from '@/api/user.js'
import router, { constantRoutes, resetRouter } from '@/router'
import { getToken, setToken } from '@/utils/auth.js'
import asyncRoutes from '@/router/modules/index.js'

const state = {
  token: getToken() || '',
  userInfo: ''
}
const mutations = {
  setUserToken (state, value) {
    state.token = value
    setToken(value)
  },
  setUserInfo (state, value) {
    state.userInfo = value
  },
  // 退出登录处理
  logout () {
    state.token = ''
    setToken('')
    state.userInfo = ''
    resetRouter() //重置路由
  }
}
const actions = {
  async toLogin ({ commit }, value) {
    const res = await login(value)
    // console.log('toLogin:', res)
    commit('setUserToken', res.data)
  },
  // 获取合并个人用户信息并存储
  async getUserInfo ({ commit, state }) {
    // 获取员工部分信息，不包含头像等信息
    const res = await sysProfile()
    // 通过userId获取其他信息
    const res2 = await sysUser(res.data.userId)
    commit('setUserInfo', { ...res.data, ...res2.data })
    const newArr = asyncRoutes.filter(item => {
      return state.userInfo.roles.menus.includes(item.name)
    })
    // 因为添加路由不能立马使用，它会立马匹配404，所经需要404匹配路由动态添加
    newArr.push({ path: '*', redirect: '/404', hidden: true })
    console.log('newArr', newArr)
    commit('routes/setRoutesList', [...constantRoutes, ...newArr], {
      root: true
    })
    // 将匹配项添加到路由配置中，router.addRoutes([配置路由])，添加新的路由配置
    router.addRoutes(newArr)
    // console.log('用户信息', res, res2)
  }
}
const getters = {}
export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}
